<?php
class Membership_model extends MY_Model {

    function __construct()
    {
        parent::__construct();
    }
    
    function get($data)
    {
    	$this->db->where('mail', $data['email']);
    	return $this->db->get('membership')->row();
    }
    
	function update_alias($data)
    {
    	$this->db->set('alias', $data['alias']);
    	if (isset($data['key']) && $data['key'] != '')
    	{
    		$this->db->set('key', $data['key']);
    		$this->session->set_userdata(array('key' => $data['key']));
    	}
    	
    	$this->db->where('id', $data['idmember']);
    	
    	return $this->db->update('membership');
    }
    
	function insert($data)
    {
		$this->load->helper('password');

		$this->db->trans_begin();
		
		$member_data = array(
		   'mail' => $data['email'],
		   'password' => encrypt_password($data['pass']),
		   'idtype' => $data['idtype']
		);
		
		$this->db->insert('membership', $member_data);
		$data['idmember'] = $this->db->insert_id();
		$this->session->set_userdata(array('idmember' => $data['idmember']));
		
		switch ($data['idtype'])
		{
			case 2:
				$this->load->model('Company_model', 'company');
				$this->company->insert($data);
				$this->session->set_userdata(array('idprofile' => $this->db->insert_id()));
				
				$data['key'] = md5($this->session->userdata['idmember'] . $data['email']);
				$this->update_alias(array('alias' => $data['key'], 'key' => $data['key'], 'idmember' => $this->session->userdata['idmember']));
				
				$this->make_dirs();
				break;
				
			case 3:
				$this->load->model('Education_model', 'education');
				$this->education->insert($data);
				$this->session->set_userdata(array('idprofile' => $this->db->insert_id()));
				
				$data['key'] = md5($this->session->userdata['idmember'] . $data['email']);
				$this->update_alias(array('alias' => $data['key'], 'key' => $data['key'], 'idmember' => $this->session->userdata['idmember']));
				
				$this->make_dirs();
				break;
		
			case 1:
			default:
				$this->load->model('Candidate_model', 'candidate');
				$this->candidate->insert($data);
				$this->session->set_userdata(array('idprofile' => $this->db->insert_id()));
				
				$data['key'] = md5($this->session->userdata['idmember'] . $data['email']);
				$this->update_alias(array('alias' => $data['key'], 'key' => $data['key'], 'idmember' => $this->session->userdata['idmember']));
				
				$this->make_dirs();
				break;
		}
		
    	if ($this->db->trans_status() === false)
		{
		    $this->db->trans_rollback();
		    return false;
		}
		else
		{
		    $this->db->trans_commit();
		    return true;
		}
    }
    
    function insert_login($data)
    {
    	$this->db->set('date', 'NOW()', false);
		return $this->db->insert('membership_login', $data);
    }
}
?>